import { postFoo } from '@/service/index/foo'
import { useUserStore } from '@/store'

/**
 * 微信登录
 * @param loginUrl 登录地址
 */
export const useWxLogin = (loginUrl = '/api/login') => {
  const userStore = useUserStore()

  return new Promise<Record<string, any>>((resolve, reject) => {
    try {
      uni.login({
        provider: 'weixin', // 使用微信登录
        success: async (loginRes) => {
          if (!loginRes.code) {
            console.log(`🚀 ~ loginRes: login_not_code`, loginRes)
            return reject(new Error('微信授权失败'))
          }

          const { token, user } = await postFoo({
            url: loginUrl,
            data: { openidCode: loginRes.code },
            hideRequestLoading: true,
          })

          userStore.setToken(token)
          userStore.setUserInfo(user)
          resolve(user)
        },
        fail: (error) => {
          console.error('uni.login failed:', error)
          reject(error) // 登录失败时 reject
        },
      })
    } catch (error) {
      console.log(`🚀 ~ useWxLogin ~ error:`, error)
      reject(error) // 捕获其他异常并 reject
    }
  })
}
/**
 * 微信支付
 * @param payUrl 调起支付请求地址
 * @param payData 请求体
 * @returns
 */
export const useWxPay = (payUrl = '/api/order/pay', payData: Record<string, any>) => {
  return new Promise<void>((resolve, reject) => {
    const run = async () => {
      try {
        const { data } = await postFoo({
          url: payUrl,
          data: payData,
          hideRequestLoading: true,
        })

        uni.requestPayment({
          provider: 'wxpay',
          orderInfo: {
            appId: data.appId,
            noncestr: data.nonceStr,
            package: data.package,
            timestamp: data.timeStamp,
            sign: data.paySign,
          },
          timeStamp: data.timeStamp,
          nonceStr: data.nonceStr,
          package: data.package,
          signType: 'RSA',
          paySign: data.paySign,
          success: () => {
            resolve()
          },
          fail: (err) => {
            console.log('🚀 ~ orderHandle ~ err:', err)
            reject(err)
          },
        })
      } catch (error) {
        console.log(`🚀 ~ useWxPay ~ error:`, error)
        reject(error)
      }
    }

    run()
  })
}
